package models

import "github.com/astaxie/beego/orm"

type TableModel struct {
	Tablename  string
	Tableowner string
}

type TableDetail struct {
	Comment string
	Type string
	Name string
	Notnull string
	Conname string
}


type JavaCode struct {
	TableName    string
	TableComment string
	ClassName    string
	PackageName string
	Fields       []JavaTableField
}

type JavaTableField struct {
	Message string
	Length string
	Type string
	FieldName string
	Comment string
	TableFieldComment string
	NullAble string
}

func GetTableDetail(table string)([]TableDetail, error)  {
	sql := "SELECT " +
			"col_description ( A.attrelid, A.attnum ) AS COMMENT, " +
			"format_type ( A.atttypid, A.atttypmod ) AS TYPE, " +
			"A.attname AS NAME, " +
			"A.attnotnull AS NOTNULL, " +
			"D.conname AS CONNAME " +
		"FROM " +
			"pg_class AS C " +
		"INNER JOIN " +
			"pg_attribute AS A " +
		"ON " +
			"A.attrelid = C.oid " +
		"LEFT JOIN " +
			"pg_constraint AS D " +
		"ON " +
			"D.conrelid = C.oid " +
		"AND " +
			"D.contype = 'p' " +
		"AND " +
			"A.attnum = D.conkey [ 1 ] " +
		"WHERE " +
			"C.relname = ? " +
		"AND " +
			"A.attnum > 0 "
	o := orm.NewOrm()
	var tabledetail []TableDetail
	var err error
	_, err = o.Raw(sql, table).QueryRows(&tabledetail)
	return tabledetail, err
}

func GetAllTable() ([]TableModel, error) {
	o := orm.NewOrm()
	sql := "select tablename, tableowner from pg_tables where schemaname = 'public'"
	tables := []TableModel{}
	_, err := o.Raw(sql).QueryRows(&tables)

	return tables,err
}
